package fr.kraml;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;

public class Participant {

	public String username, show, status, sex, location, avatar;
	public int age;
	public Drawable avatarBMP;
	ParticipantFragment pf;

	public Participant(ParticipantFragment pf, String username, String show, String status, int age,
			String sex, String location, String avatar) {
		// TODO Auto-generated constructor stub
		this.pf = pf;
		this.username = username;
		this.show = show;
		this.status = status;
		this.age = age;
		this.sex = sex;
		this.location = location;
		this.avatar = avatar;

		if (pf != null) new RetreiveImage().execute("http://kraml.fr/" + avatar);
	}

	public String getASV() {
		// TODO Auto-generated method stub
		return age + ", " + sex + ", " + location;
	}
	
	public static Drawable drawableFromUrl(String url) throws IOException {
	    Bitmap x;

	    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
	    connection.connect();
	    InputStream input = connection.getInputStream();

	    x = BitmapFactory.decodeStream(input);
	    return new BitmapDrawable(x);
	}
	
	class RetreiveImage extends AsyncTask<String, Void, Drawable> {

	    protected Drawable doInBackground(String... urls) {
	        try {
	            String url= urls[0];
	            Log.i("DoInBackground", url);
	            return drawableFromUrl(url);
	        } catch (Exception e) {
	            return null;
	        }
	    }

	    protected void onPostExecute(Drawable draw) {
	        // TODO: check this.exception 
	        // TODO: do something with the feed
	    	Log.i("PostExec", "");
	    	avatarBMP = draw;
	    	//pf.reload();
			pf.adapter.notifyDataSetChanged();
	    	//lv.setAdapter(adapter);
	    	//ParticipantFragment.adapter.notifyDataSetChanged();
	    }
	}

}
